//
//  LessonViewController.m
//  Pr2
//
//  Created by Qingxin Xuan on 9/12/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "LessonViewController.h"
#import "ScrollableItem.h"
#import "Lesson.h"
#import "PropertyItem.h"
#import "MovableView.h"
#import "LBYouTubePlayerViewController.h"

#define  PROPERTY_ITEM_VIEW_HEIGHT          30

@interface LessonViewController ()

@end

@implementation LessonViewController
@synthesize thumbScrollView;
@synthesize imgView;
@synthesize lblTitle;
@synthesize lesson;

@synthesize vwLeftProperty;
@synthesize vwRightProperty;

@synthesize dragSourceView;
@synthesize dragTargetView;
@synthesize movingView;
@synthesize contentView;

@synthesize origSrcViewCenter;
@synthesize vController;
@synthesize activity;

@synthesize lblDescription;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear: animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSMutableArray* urls = [NSMutableArray arrayWithObjects: 
                            @"http://t3.baidu.com/it/u=2081158035,745469975&fm=15&gp=0.jpg",
                            @"http://whatsup.meiku.org/files/2011/08/aa1903-150x150.jpg",
                            @"http://t2.baidu.com/it/u=3245092967,220526567&fm=15&gp=0.jpg",
                            @"http://whatsup.meiku.org/files/2011/11/931ahqdefault-150x150.jpg",
                            @"http://image.rayli.com.cn/extend/2011-04-02/13159300278689235754.jpg",
                            @"http://whatsup.meiku.org/files/2011/08/14fb04-150x150.jpg",
                            @"http://img.ifeng.com/itvimg/2008/09/27/161edc59-80f2-41e4-86c3-71a268811965.jpg",
                            @"http://www.80g.cc/file/upload/201209/12/16-20-01-48-20270.jpg.middle.jpg",
                            @"http://image4.rayliimg.cn/0003/2012-02-01/images/20120201175545189.jpg",                           
                            @"http://a1.att.hudong.com/37/15/300000876508130525158771134_950.jpg",
                            @"http://pic.newssc.org/0/11/93/90/11939086_945269.jpg",
                            @"http://www.dfhon.com/NewsImages/20090814/200908141715248160.jpg",nil];
    int urlCount = [urls count];
    
    NSMutableArray* array = [NSMutableArray array];
    for (int i=0; i<30; i++) {
        ScrollableItem* item = [ScrollableItem new];
        item.title = [NSString stringWithFormat: @"Student %d", i];
        item.thumbnailURL = [urls objectAtIndex: i%urlCount];
        [array addObject: item];
    }
    [self.thumbScrollView resetWithScrollableItems: array];
    self.thumbScrollView.delegate = self;
    self.imgView.image = [UIImage imageNamed: @"no_image.png"];

    if (self.lesson == nil) {
        self.lesson = [Lesson new];
    }
    [self resetPropertyLists];
}

- (void) removeAllSubView: (UIView*) vwTarget
{
    for (UIView* subview in vwTarget.subviews) {
        [subview removeFromSuperview];
    }
}

- (void) resetPropertyLists
{
    [self removeAllSubView: self.vwLeftProperty];
    [self removeAllSubView: self.vwRightProperty];
    
    const int height = PROPERTY_ITEM_VIEW_HEIGHT;
    int width = self.vwLeftProperty.frame.size.width;
    
    int lcount = [self.lesson.leftProperties count];
    for (int i=0; i<lcount; i++) {
        PropertyItem* item = [self.lesson.leftProperties objectAtIndex: i];
        MovableView* mview = [[MovableView alloc] initWithItem: item];
        mview.frame = CGRectMake(0, i*height, width, height);
        mview.tag = i+1;
        [self.vwLeftProperty addSubview: mview];
    }

    width = self.vwRightProperty.frame.size.width;
    int rcount = [self.lesson.rightProperties count];
    for (int i=0; i<rcount; i++) {
        PropertyItem* item = [self.lesson.rightProperties objectAtIndex: i];
        MovableView* mview = [[MovableView alloc] initWithItem: item];
        mview.frame = CGRectMake(0, i*height, width, height);
        mview.tag = i+1;
        [self.vwRightProperty addSubview: mview];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}

#pragma mark ThumbScrollView Delegate

- (void) clickedOnIndex:(NSInteger)index
{
    ScrollableItem* item = [self.thumbScrollView.arrayOfItems objectAtIndex: index];
    self.imgView.image = item.thumbnail;
    self.lblTitle.text = item.title;
}

#pragma mark Touch Event

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch* touch = [touches anyObject];
    
    CGPoint pt = [touch locationInView: self.view];
    if (CGRectContainsPoint(self.vwLeftProperty.frame, pt)) {
        self.dragSourceView = self.vwLeftProperty;
        self.dragTargetView = self.vwRightProperty;
    }
    else if (CGRectContainsPoint(self.vwRightProperty.frame, pt)){
        self.dragSourceView = self.vwRightProperty;
        self.dragTargetView = self.vwLeftProperty;
    }
    else
    {
        self.dragSourceView = nil;
        self.dragTargetView = nil;
    }
    
    if (dragSourceView == nil) {
        return;
    }
    
    CGPoint ptInSourceView = [touch locationInView: self.dragSourceView];
    int nIndex = ptInSourceView.y / PROPERTY_ITEM_VIEW_HEIGHT;
    self.movingView = [self.dragSourceView viewWithTag: nIndex + 1];
    [self.view addSubview: self.movingView];
    
    self.origSrcViewCenter = self.movingView.center;
    
    self.movingView.center = pt;
}

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (self.movingView == nil || self.dragTargetView == nil) {
        return;
    }
    
    UITouch* touch = [touches anyObject];
    CGPoint pt = [touch locationInView: self.view];
    self.movingView.center = pt;
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (self.movingView == nil || self.dragTargetView == nil) {
        return;
    }
    
    UITouch* touch = [touches anyObject];
    CGPoint pt = [touch locationInView: self.view];
    
    if (CGRectContainsPoint(self.dragTargetView.frame, pt)) {
        NSMutableArray* srcArray, *dstArray;
        if (self.dragTargetView == self.vwRightProperty) {
            srcArray = self.lesson.leftProperties;
            dstArray = self.lesson.rightProperties;
        }
        else
        {
            srcArray = self.lesson.rightProperties;
            dstArray = self.lesson.leftProperties;
        }
        
        MovableView* mView = (MovableView*)self.movingView;
        PropertyItem* item = mView.item;
        [srcArray removeObject: item];
        [dstArray addObject: item];
        [self resetPropertyLists];
        [mView removeFromSuperview];
    }
    else{
        [self.dragSourceView addSubview: self.movingView];
        self.movingView.center = self.origSrcViewCenter;
        [self onMovingViewClicked: (id)self.movingView];
    }
}

- (void) onMovingViewClicked: (MovableView*) mview
{
    if (mview.superview == self.vwRightProperty) {
        self.lblTitle.text = mview.item.title;
        self.lblDescription.frame = CGRectMake(802, 183, 214, 0);
        self.lblDescription.numberOfLines = 0;
        self.lblDescription.text = mview.item.description;
        [self.lblDescription sizeToFit];
    }
    else
    {
        if ([self.activity isAnimating]) {
        return;
        }
    
        [self.activity startAnimating];
        self.imgView.hidden = YES;
        NSLog(@"Move View - %@", mview.item.link);
        [self removeAllSubView: self.contentView];
    
        self.vController = [[LBYouTubePlayerViewController alloc] initWithYouTubeURL:[NSURL URLWithString: mview.item.link] quality:LBYouTubeVideoQualityLarge];
        vController.delegate = self;
        vController.view.frame = self.contentView.bounds;
        [self.contentView addSubview: vController.view];
    }
}

#pragma mark -
#pragma mark LBYouTubePlayerViewControllerDelegate

-(void)youTubePlayerViewController:(LBYouTubePlayerViewController *)controller didSuccessfullyExtractYouTubeURL:(NSURL *)videoURL {
    NSLog(@"Did extract video source:%@", videoURL);
    [self.activity stopAnimating];
}

-(void)youTubePlayerViewController:(LBYouTubePlayerViewController *)controller failedExtractingYouTubeURLWithError:(NSError *)error {
    NSLog(@"Failed loading video due to error:%@", error);
}

@end
